import pygame

import stackless
import select,sys

from event import Event

class Controller:

    def __init__(self,world_):

        self.world=world_
        self.tasklet=stackless.tasklet(self.get_input)()

class TextController(Controller):
    def get_input(self):
        while True:
            reader,fout,error=select.select([sys.stdin],[],[],0.02)

            if reader:
                reader = reader[0]
                content=reader.readline().strip()

                subject='quit' if content=='quit' else 'input'

                self.world.channel.send(
                        Event(subject=subject,queue=[content])
                        )

                if subject=='quit' : break

            stackless.schedule()

from pygame.locals import *

class PyGameController(Controller):

    keys={
            pygame.K_LEFT:'left',
            pygame.K_RIGHT:'right',
            pygame.K_UP:'up',
            pygame.K_DOWN:'down',
            pygame.K_SPACE:'set'
            }

    def get_input(self):

        while True:

            pygame.init()

            for event in pygame.event.get():
                if event.type==QUIT:
                    self.world.channel.send(Event(subject='quit'))
                elif event.type==KEYDOWN:

                    if event.key in self.keys :
                        cmd=self.keys[event.key]

                        self.world.channel.send(Event(subject='input',queue=[cmd]))

            stackless.schedule()
